import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Painter extends JFrame implements ActionListener, MouseMotionListener {
    JPanel canvas;
    JMenu clear,pen,color;
    JMenuBar jMenuBar;
    JMenuItem eraser,clean,exit;
    JRadioButtonMenuItem red,blue,green;
    ButtonGroup buttonGroup;
    Graphics g;
    Color c;
    public Painter(){
        setSize(800,600);
        setTitle("我的小小画板");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        c = Color.BLACK;
        canvas = new JPanel();
        canvas.setBackground(Color.white);
        jMenuBar = new JMenuBar();
        clear =new JMenu("清除方式");
        eraser = new JMenuItem("橡皮");
        clean = new JMenuItem("清除");
        exit = new JMenuItem("退出");
        clear.add(eraser);
        clear.add(clean);
        clear.addSeparator();
        clear.add(exit);
        pen = new JMenu("画笔选择");
        color = new JMenu("颜色");
        red = new JRadioButtonMenuItem("红色");
        blue = new JRadioButtonMenuItem("蓝色");
        green = new JRadioButtonMenuItem("绿色");
        buttonGroup = new ButtonGroup();
        buttonGroup.add(red);
        buttonGroup.add(blue);
        buttonGroup.add(green);
        color.add(red);
        color.add(blue);
        color.add(green);
        pen.add(color);
        jMenuBar.add(clear);
        jMenuBar.add(pen);
        add(canvas);
        setJMenuBar(jMenuBar);
        eraser.addActionListener(this);
        clean.addActionListener(this);
        exit.addActionListener(this);
        red.addActionListener(this);
        blue.addActionListener(this);
        green.addActionListener(this);
        addMouseMotionListener(this);
        setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() == eraser){
            //橡皮
            c = canvas.getBackground();
        }else if(e.getSource() == clean){
            //清除
            g.setColor(getBackground());
            g.fillRect(0,60,800,600);

            canvas.setBackground(Color.white);
        }else if(e.getSource() == exit){
            //退出
            System.exit(0);
        }else if(e.getSource() == red){
            //红色
            c = Color.red;
        }else if(e.getSource() == blue){
            //蓝色
            c = Color.blue;
        }else{
            //绿色
            c = Color.green;
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {
        g = getGraphics();
        g.setColor(c);
        g.fillOval(e.getX()-3,e.getY()-3,6,6);
    }

    @Override
    public void mouseMoved(MouseEvent e) {

    }
}


